package com.hy.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.hy.base.DozerBase;
import com.hy.dao.AreaMapper;
import com.hy.dao.AreaMapper_My;
import com.hy.exception.ExceptionEnum;
import com.hy.exception.ServiceException;
import com.hy.form.input.AreaAddForm;
import com.hy.form.result.AreaResultForm;
import com.hy.model.Area;
import com.hy.model.AreaExample;
import com.hy.service.IAreaService;

@Service
public class AreaServiceImpl extends DozerBase implements IAreaService {
	
	static final Logger logger = LoggerFactory.getLogger(AreaServiceImpl.class);

	@Autowired
	AreaMapper areaMapper;
	
	@Autowired
	AreaMapper_My areaMapper_My;
	
	@Override
	public void add(AreaAddForm areaAddForm) {
		Area area = this.getDozerMapper().map(areaAddForm, Area.class);
		if(StringUtils.isEmpty(areaAddForm.getGuid())){
			/*AreaExample areaExample = new AreaExample();
			int count = areaMapper.selectByPrimaryKey(areaAddForm.getCode());
			if(count > 0) {
				throw new ServiceException(ExceptionEnum.CODE_REPEAT);
			}*/
			area.setGuid(UUID.randomUUID().toString());
			Date date = new Date();
			area.setCreate_time(date);
			area.setUpdate_time(date);
			areaMapper.insertSelective(area);
		} else {
			/*AreaExample areaExample = new AreaExample();
			areaExample.or().andCodeEqualTo(areaAddForm.getCode());
			List<Area> list = areaMapper.selectByExample(areaExample);
			if(!list.isEmpty() && list.get(0).getCode().equals(areaAddForm.getCode())){
				throw new ServiceException(ExceptionEnum.CODE_REPEAT);
			}*/
			Date date = new Date();
			area.setUpdate_time(date);
			areaMapper.updateByPrimaryKeySelective(area);
		}
	}

	@Override
	public void del(String guid) {
		logger.info("del>>>guid:" + guid);
		Area area = areaMapper.selectByPrimaryKey(guid);
		if(area == null){
            throw new ServiceException(ExceptionEnum.RECORD_NOT_EXIST);
        }
		
		//判断是否有子节点，有则不能删除
		AreaExample areaExample = new AreaExample();
		areaExample.or().andParent_guidEqualTo(guid);
		int count = areaMapper.countByExample(areaExample);
		if(count > 0){
            throw new ServiceException(ExceptionEnum.RECORD_HAS_LEAF_NODE);
        }
		
		areaMapper.deleteByExample(areaExample);
	}

	@Override
	public Area info(String guid) {
		logger.info("info>>>guid:" + guid);
		Area area = areaMapper.selectByPrimaryKey(guid);
		if(area == null){
            throw new ServiceException(ExceptionEnum.RECORD_NOT_EXIST);
        }
		return area;
	}

	@Override
	public List<AreaResultForm> list() {
		//查出所有区域
		List<AreaResultForm> areaList = areaMapper_My.queryArea(new HashMap<String, Object>());
		//没有区域信息
        if(CollectionUtils.isEmpty(areaList)){
            return null;
        }
       
        Map<String,List<AreaResultForm>> map = new TreeMap<String,List<AreaResultForm>>();
        
        List<AreaResultForm> topNodes = new ArrayList<AreaResultForm>();
        
        for(AreaResultForm areaNode : areaList){
            //查询顶级节点
            if("0".equals(areaNode.getParent_guid())){
                topNodes.add(areaNode);
            } else {
            	String parent_guid = areaNode.getParent_guid();
            	if( map.containsKey(parent_guid)) {
            		map.get(parent_guid).add(areaNode);
            	} else {
            		List<AreaResultForm> nodes = new ArrayList<AreaResultForm>();
            		nodes.add(areaNode);
            		map.put(parent_guid, nodes);
            	}
            }
        }
        
        map.put("topNodes", topNodes);
        
        //返回值
        List<AreaResultForm> result = new ArrayList<AreaResultForm>();
        //按规则得到菜单集合
        if(!CollectionUtils.isEmpty(topNodes)){
            //遍历顶级节点
            for(AreaResultForm areaNode : topNodes){
                getChildNodeList(map, areaNode, result);
            }
        }
        return result;
	}
	
	/**
     * 向下递归查询集合中的参数节点的子节点，以list结构返回
     *
     * @param allAreaGuids 所有节点guid集合
     * @param node 指定节点
     * @param result 返回结果
     * @return
     */
    private List<AreaResultForm> getChildNodeList(Map<String,List<AreaResultForm>> map ,
    		AreaResultForm node, List<AreaResultForm> result){
        if(CollectionUtils.isEmpty(map)){
            return null;
        }
        //添加节点
        result.add(node);
        //guid
        String area_guid = node.getGuid();
        //查询符合条件的子节点
        
        List<AreaResultForm> menuList = map.get(area_guid);
        if (!CollectionUtils.isEmpty(menuList)) {
            for(AreaResultForm childMenu : menuList){
                getChildNodeList(map, childMenu, result);
            }
        } else {
            node.setIsLeaf(true);
        }
        return result;
    }

}
